﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices; 

namespace volumn
{
    public partial class Form1 : Form
    {
        [DllImport("winmm.dll")]
        public static extern long waveOutSetVolume(UInt32 deviceID, UInt32 Volume);
        [DllImport("winmm.dll")]
        public static extern long waveOutGetVolume(UInt32 deviceID, out UInt32 Volume);


        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam);
        const uint WM_APPCOMMAND = 0x319;
        const uint APPCOMMAND_VOLUME_UP = 0x0a;
        const uint APPCOMMAND_VOLUME_DOWN = 0x09;
        const uint APPCOMMAND_VOLUME_MUTE = 0x08;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 设置滑块值为当前音量的值  
            GetVolume();
        }

        // 设置当前音量值到滑动条上  
        private void GetVolume()
        {
            UInt32 d, v;
            d = 0;
            long i = waveOutGetVolume(d, out v);
            UInt32 vleft = v & 0xFFFF;
            UInt32 vright = (v & 0xFFFF0000) >> 16;
            trackBar1.Value = (int.Parse(vleft.ToString()) | int.Parse(vright.ToString())) * (this.trackBar1.Maximum - this.trackBar1.Minimum) / 0xFFFF;
        }
        // 滑块值改变时，修改音量值  
        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            UInt32 Value = (System.UInt32)((double)0xffff * (double)trackBar1.Value / (double)(trackBar1.Maximum - trackBar1.Minimum));//先把trackbar的value值映射到0x0000～0xFFFF范围    
            //限制value的取值范围    
            if (Value < 0) Value = 0;
            if (Value > 0xffff) Value = 0xffff;
            UInt32 left = (System.UInt32)Value;//左声道音量    
            UInt32 right = (System.UInt32)Value;//右    
            waveOutSetVolume(0, left << 16 | right); //"<<"左移，“|”逻辑或运算    
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //加音量
            SendMessage(this.Handle, WM_APPCOMMAND, 0x30292, APPCOMMAND_VOLUME_UP * 0x10000);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //减音量
            SendMessage(this.Handle, WM_APPCOMMAND, 0x30292, APPCOMMAND_VOLUME_DOWN * 0x10000);
        }


        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            //静音
            SendMessage(this.Handle, WM_APPCOMMAND, 0x200eb0, APPCOMMAND_VOLUME_MUTE * 0x10000);
        }
    }   
}
